﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using DB = HTComics.Data;
using Newtonsoft.Json;
using System.Data;
using System.IO;
using HTComics.Web.Common;
using System.Net.Mail;

namespace HTComics.Web.Order
{
    public partial class SubmitOrder : System.Web.UI.Page
    {
        protected string orderCode;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UID"] == null)
            {
                Response.Redirect("~/User/Login.aspx?ord=1");
            }

            string orderId;
            orderId = DB.Order.CreateOrder(Session["UID"].ToString(), out orderCode);

            double discount = DB.Misc.GetGlobalDiscount();
            double sellPrice, discountPrice, totalPrice=0;
            int qty;
            DataSet dsResult;
            StringBuilder tblCart = new StringBuilder();
            Dictionary<string, Dictionary<string, Dictionary<string, string>>> data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(Server.UrlDecode(Request.Cookies["cart"].Value));

            foreach (string comicId in data.Keys)
            {
                foreach (string issue in data[comicId].Keys)
                {
                    foreach (string condition in data[comicId][issue].Keys)
                    {
                        qty = Convert.ToInt32(data[comicId][issue][condition]);
                        if (qty > 0)
                        {
                            dsResult = DB.Search.GetIssueDetails(comicId, issue, condition);

                            string imgLoc = dsResult.Tables[0].Rows[0][0].ToString()[0] + "/" + dsResult.Tables[0].Rows[0][0];
                            string img;

                            if (File.Exists(HttpContext.Current.Server.MapPath("~/Images/Covers/" + imgLoc + "/" + issue + ".jpg")))
                                img = "<a href='#'><img id='img" + issue + "' src=\"http://" + Defaults.DomainName + "/Images/Covers/" + imgLoc.Replace(" ","%20") + "/" + issue + ".jpg\" height='60px' width='45px' onclick=showDetails(this) border='0' cn=\"" + dsResult.Tables[0].Rows[0]["Title"] + "\" issue='" + issue + "' cp='" + dsResult.Tables[0].Rows[0]["CoverPrice"] + "' sl='" + dsResult.Tables[0].Rows[0]["Storylines"] + "' wrt='" + dsResult.Tables[0].Rows[0]["Writer"] + "' art='" + dsResult.Tables[0].Rows[0]["Artist"] + "' cd='" + Convert.ToDateTime(dsResult.Tables[0].Rows[0]["CoverDate"]).ToString("MMM yyyy") + "'/></a>";
                            else
                                img = "<img src='http://" + Defaults.DomainName + "/Images/noimage.png' height='30px' width='22px' />";

                            sellPrice = Convert.ToDouble(dsResult.Tables[1].Rows[0]["SellingPrice"]);
                            sellPrice = Pricing.CalculatePrice(sellPrice, Convert.ToInt32(dsResult.Tables[1].Rows[0]["ConditionId"]));

                            sellPrice *= qty;

                            DB.Order.CreateOrderDetails(orderId, comicId, issue, condition, qty, sellPrice, discount);

                            discountPrice = sellPrice - (sellPrice * discount / 100);

                            sellPrice *= qty;
                            discountPrice *= qty;

                            sellPrice = Math.Round(sellPrice, 2);
                            discountPrice = Math.Round(discountPrice, 2);

                            tblCart.Append("<tr>");
                            tblCart.Append("<td class='isuDetRow_L'>" + img + "</td>");
                            tblCart.Append("<td class='isuDetRow_M'>" + dsResult.Tables[0].Rows[0]["Title"] + "</td>");
                            tblCart.Append("<td class='isuDetRow_M'>" + issue + "</td>");
                            tblCart.Append("<td class='isuDetRow_M'>" + dsResult.Tables[1].Rows[0]["Name"] + "</td>");
                            tblCart.Append("<td class='isuDetRow_M'>" + data[comicId][issue][condition] + "</td>");

                            if (discount > 0)
                            {
                                tblCart.Append("<td class='isuDetRow_M'><del>€" + string.Format("{0:0.00}", sellPrice) + "</del></td>");
                                tblCart.Append("<td class='isuDetRow_M'>€" + string.Format("{0:0.00}", discountPrice) + "</td>");
                                tblCart.Append("<td class='isuDetRow_M'>€" + string.Format("{0:0.00}", (sellPrice - discountPrice)) + "</td>");

                                totalPrice += discountPrice;
                            }
                            else
                            {
                                tblCart.Append("<td class='isuDetRow_M'>€" + string.Format("{0:0.00}", sellPrice) + "</td>");
                                totalPrice += sellPrice;
                            }

                            tblCart.Append("</tr>");
                        }
                    } //Condition
                } //Issue
            } //ComiId
            
            content.InnerHtml = content.InnerHtml.Replace("ORDER_CODE", orderCode);

            SendCustomerEmail(tblCart.ToString(), orderCode, totalPrice);
            SendAdminEmail(tblCart.ToString(), orderCode, totalPrice, "jk_comics@yahoo.com");
            SendAdminEmail(tblCart.ToString(), orderCode, totalPrice, "dublincitycomics@yahoo.com");
        }

        public void SendCustomerEmail(string tblCart, string orderCode, double totalPrice)
        {
            SmtpClient client = new SmtpClient();
            StringBuilder objHtml = new StringBuilder();

            client.Host = Defaults.MailSetup.MailServer;
            client.Port = Defaults.MailSetup.MailPort;

            MailMessage msg = new MailMessage();
            msg.IsBodyHtml = true;

            objHtml.Append("<html>");
            objHtml.Append("<body>");
            objHtml.Append("<b>Order Code</b>: " + orderCode + "<br />");
            objHtml.Append("<b>Total Price</b>: €" + Math.Round(totalPrice, 2) + "<br />");
            objHtml.Append("<table border=1>");
            objHtml.Append(tblCart);
            objHtml.Append("</table>");
            objHtml.Append("</body>");
            objHtml.Append("</html>");

            msg.Body = objHtml.ToString();
            msg.Subject = "[" + Defaults.DomainName  + "] Order Code: " + orderCode;
            msg.From = new MailAddress(Defaults.MailSetup.OrdersAccount);
            msg.To.Add(new MailAddress(Session["Email"].ToString()));

            client.Send(msg);
        }

        public void SendAdminEmail(string tblCart, string orderCode, double totalPrice, string adminEml)
        {
            SmtpClient client = new SmtpClient();
            StringBuilder objHtml = new StringBuilder();

            client.Host = Defaults.MailSetup.MailServer;
            client.Port = Defaults.MailSetup.MailPort;

            MailMessage msg = new MailMessage();
            msg.IsBodyHtml = true;

            objHtml.Append("<html>");
            objHtml.Append("<body>");
            objHtml.Append("<b>Order Code</b>: " + orderCode + "<br />");
            objHtml.Append("<b>Total Price</b>: €" + Math.Round(totalPrice, 2) + "<br />");
            objHtml.Append("<b>User Name:</b>: " + Session["FirstName"] + " " + Session["LastName"] + "<br />");
            objHtml.Append("<b>User Email</b>: " + Session["Email"] + "<br /><br /><br />");
            objHtml.Append("<table border=1>");
            objHtml.Append(tblCart);
            objHtml.Append("</table>");
            objHtml.Append("</body>");
            objHtml.Append("</html>");

            

            msg.Body = objHtml.ToString();
            msg.Subject = "New Order Received Order Code: " + orderCode;
            msg.From = new MailAddress(Defaults.MailSetup.NoReplyAccount);
            msg.To.Add(new MailAddress(adminEml));

            client.Send(msg);
        }
    }
}